package com.soa.zuul.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.zip.GZIPInputStream;

import com.netflix.util.Pair;

public class ZipStreamUtil {

	public static String getStringFromGZIPInputStream(InputStream stream,String chartset) throws IOException{
		 GZIPInputStream gzin = new GZIPInputStream(stream);
		 InputStreamReader isr = new InputStreamReader(gzin,chartset);
		 java.io.BufferedReader br = new java.io.BufferedReader(isr);
		 String tempbf;
         StringBuffer sb = new StringBuffer();
         while ((tempbf = br.readLine()) != null) {
             sb.append(tempbf);
         }
         isr.close();
         gzin.close();
         br.close();
         return sb.toString();
	}
	
	public static String getEncoding (List<Pair<String, String>> list){
		String encoding ="UTF-8"; 
		for (Pair<String, String> pair : list) {
			if(pair.first().equalsIgnoreCase("Content-Type")){
				if(pair.second().indexOf("=")!=-1){
					String[] ch = pair.second().split("=");
					if(ch.length>1 && ch[1]!=null){
						encoding=ch[1];
					}
				}
			}
		}
		return encoding;
	}
	
	public static ByteArrayOutputStream  getByteArrayOutputStream(InputStream stream){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();  
		byte[] buffer = new byte[2048];  
		int len;  
		try {
			while ((len = stream.read(buffer)) > -1 ) {  
			    baos.write(buffer, 0, len);  
			}
			baos.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return baos;
	}
}
